﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Media;

namespace Algoritmos_de_Ordenação.Algoritmos
{
    public class InsertionSort : DrawingRegion
    {
        public InsertionSort()
        {
        }
        public InsertionSort(TabItem tabItem)
            : base(tabItem, TabType.Insertion)
        {
        }

        protected override void DoSort()
        {

            int comparisons = 0;
            int swaps = 0;          
            
            sorted = false;

            for (int i = 1; i < numElemArray; i++)//3
            {
                int valor = numberArray[i];
                int j = i - 1;

                bool alteredJ = false;
                
                while ((j >= 0) && (numberArray[j] > valor))//8
                {
                    alteredJ = true;
                    
                    wf();
                    updateGBThread(7);
                    compareTwoWithFixedThread(j+1, j, i, valor);
                    comparisons++;
                    wf();
                    updateGBThread(9);
                    swaps++;
                    updateInformationsThread(SortStatus.Sorting, comparisons, swaps);
                    numberArray[j + 1] = numberArray[j];//10
                    compareTwoWithFixedThread(j + 1, j, i, valor);
                    j--;
                }
                
                wf();
                updateGBThread(7);
                if (alteredJ)
                {
                    compareTwoWithFixedThread(j + 1, j + 1, i, valor);
                }
                else compareTwoWithFixedThread(j + 1, j, i, valor);                    
                
                comparisons++;
                updateInformationsThread(SortStatus.Sorting, comparisons, swaps);
                
                wf ();
                updateGBThread(13);
               
                swaps++;
                updateInformationsThread(SortStatus.Sorting, comparisons, swaps);
                numberArray[j + 1] = valor;//14
                compareTwoWithFixedThread(i, j + 1, i, valor);
            }
            endSorting(comparisons, swaps);

        }//DoSort()
    }
}
